package com.lej.app_main.helper

import android.Manifest
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.lej.core.base.BaseApplication
import com.lej.core.common.LOCATION
import com.lej.core.daq.DAQEvent
import com.lej.core.permission.checkWithReq
import com.lej.core.utils.KLog
import com.lej.core.utils.MMKVUtils
import com.lej.dataservice.club.data.PengPermissions
import com.lej.location.LocationHelper
import com.lej.location.LocationListener
import com.lej.location.LocationModel
import com.permissionx.guolindev.PermissionX
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 上报自己定位位置接口,无定位权限或者上次上报时间少于30min均不上传
 */
object PushLocationHelper {
    private const val intervalTime = 30 * 60 * 1000//间隔时间

    private var locationHelper: LocationHelper? = null

    private var pushTime = 0L
    fun push(immediately: Boolean = false) {
        if (!immediately && System.currentTimeMillis() - pushTime < intervalTime) {
            return
        }
        val ctx = BaseApplication.instance
        if (ContextCompat.checkSelfPermission(
                ctx.applicationContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            DAQEvent.push_location.mobEvent("not location permission")
            return
        }
        locationHelper = LocationHelper(ctx, object : LocationListener {
            override fun success(model: LocationModel) {
                MMKVUtils.getInstance().put(LOCATION, "${model.lon},${model.lat}")
                locationHelper?.stopLocation()
            }

            override fun error(msg: String) {
                DAQEvent.push_location.mobEvent("location error: $msg")
            }

            override fun noPermissions() {
            }
        }).apply {
            startLocation(ctx)
        }
    }
}

fun FragmentActivity.pushLocation(
    needReqPermission: Boolean = true,
    callBack: (Boolean) -> Unit = {}
) {
    ///不需要请求权限的话,有权限直接上传
    if (!needReqPermission) {
        if (PermissionX.isGranted(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) && PermissionX.isGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)
        )
            PushLocationHelper.push(true)
        return
    }
    ///如果未授权,请求权限且上传(页面初始化的时候如果授权了先上传一波)
    DAQEvent.get_permission.mobEvent("location")
    GlobalScope.launch {
        if (PengPermissions.location.checkWithReq(this@pushLocation)) {
            DAQEvent.get_permission.mobEvent("success")
            KLog.e("允许了权限!")
            callBack(true)
            PushLocationHelper.push(true)
        } else {
            callBack(false)
            DAQEvent.not_permission.mobEvent("location permission")
            KLog.e("未授权权限，部分功能不能使用")
        }
    }
}